# coding=utf-8
import os, xlrd
import json
import ast
from xlutils.copy import copy
"""
我不知道说点什么
"""


def read_excel(file_path,excel_name):
    '''读取Excel中的数据'''
    wb = xlrd.open_workbook(file_path) # 打开文件
    sh = wb.sheet_by_name(excel_name)  # 获取表格名称（下方的名字）
    data = []
    header = sh.row_values(0) # 获取第一列（标题）的值
    for i in range(1, sh.nrows):
        d = dict(zip(header, sh.row_values(i))) # zip将两个对应排列，dict让他们转换成字典
        data.append(d)
    return data

# 根据要去取出改行的数据
def get_excel(data,case_name):
    for i in data:
        if case_name == i['case_name']:
            return i


def add_write(path, value):
    '''追加写入'''
    workbook = xlrd.open_workbook(path)  # 打开工作簿
    sheets = workbook.sheet_names()  # 获取工作簿中的所有表格
    worksheet = workbook.sheet_by_name(sheets[0])  # 获取工作簿中所有表格中的的第一个表格
    rows_old = worksheet.nrows  # 获取表格中已存在的数据的行数
    new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
    new_worksheet = new_workbook.get_sheet(0)  # 获取转化后工作簿中的第一个表格
    for i in range(0, len(value)):
        for j in range(0, len(value[i])):
            new_worksheet.write(i + rows_old, j, value[i][j])  # 追加写入数据，注意是从i+rows_old行开始写入
    new_workbook.save(path)  # 保存工作簿



if __name__ == '__main__':
    path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    file_name = os.path.join(path, r'data\消息中心接口测试用例case.xlsx')
    data = read_excel(file_name, 'Sheet2')
    # userData = get_excel(data, '查询所有用户')
    # print (data)
    # print (userData)
    # print (userData['URL'])
    for i in data:
        a = (i['data'])

        try:
            b = ast.literal_eval(a)
            c = json.dumps(b, ensure_ascii=False)
            d = json.loads(c)
            print(type(a), a)
            print(type(b), b)
            print(type(c), c)
            print(type(d), d)
        except:
            pass

        # dict_data = ast.literal_eval(i['data'])
